<script setup lang="ts">
import {computed, onMounted, provide, ref, watch} from "vue";
import {ElMessage} from "element-plus";
import {
  getGoodsAPI,
  addSalesAPI,
  getConsigneeAPI,
  lookUnivalenceAPI
} from "@/axios/api";
import LeaveStoreItem from "@/components/form/leaveStoreItem.vue";
import Xiangshanli from "@/components/form/xiangshanli.vue";
//预览
const dialogFormVisible = ref(false)
//收货单位列表
const receiving_unitList = ref([])
//收货单位id
const rid = ref("")
//收货单位
const receiving_unit = ref("")
//收货人
const receivingPerson = ref("")
//部门
const department = ref("")
//备注
const remark = ref("")
const c_name = ref("")
//总数量
const allNumber = computed(() => {
  let total = 0
  for (let i = 0; i < addGoodAllList.value.length; i++) {
    console.log(addGoodAllList.value[i].number)
    total += Number(addGoodAllList.value[i].number)
  }
  return total
})
//总金额
const allMoney = computed(() => {
  let total = 0
  for (let i = 0; i < addGoodAllList.value.length; i++) {
    total += Number(addGoodAllList.value[i].money)
  }
  return total
})
//传输数据
const goodList = ref([])

//商品list
const addGoodAllList = ref([
  {
    //商品id
    id: "",
    c_name: "",
    //数量
    number: "",
    //商品单位
    per: "",
    //单价
    costPrice: "",
    //备注
    remark: "",
    by: 1,
    //金额
    get money(): Number {
      return parseInt(this.number) * parseInt(this.costPrice) || 0
    }
  }
])

onMounted(() => {
  getConsignee()
  getGoods()
  lookUnivalence()
})
const xiangshanli_List = ref([
  [], [], [], [], [], []
])
const perAllList = ref([])
const addPrint_xiangshanli = () => {
  const arr = ref(JSON.parse(JSON.stringify(xiangshanli_List.value)))
  for (let i = 0; i < arr.value.length; i++) {
    for (let j = 0; j < arr.value[i].length; j++) {
      if (!arr.value[i][j].id ||
          !arr.value[i][j].number ||
          !arr.value[i][j].costPrice ||
          !arr.value[i][j].per) {
        arr.value[i].splice(j, 1)
        j--
      }
    }
  }
  if (arr.value[0].length==0&&
      arr.value[1].length==0&&
      arr.value[2].length==0&&
      arr.value[3].length==0&&
      arr.value[4].length==0&&
      arr.value[5].length==0){
    ElMessage.error("商品不能为空")
    return
  }
  console.log(arr.value)
  for (let i = 0; i < xiangshanliList.value.length; i++) {
    console.log(rid.value)
    console.log(xiangshanliList.value[i].receivingPerson)
    console.log(xiangshanliList.value[i].department)
    console.log(xiangshanli_List.value[i])
    if (arr.value[i].length!=0){
      // index++
      addSalesAPI({
        rId: rid.value,
        receivingPerson: xiangshanliList.value[i].receivingPerson || "空",
        department: xiangshanliList.value[i].department,
        remark: ""
      }, {
        stockList: arr.value[i]
      }).then(data => {
        console.log(data)
        ElMessage.success(data.data.data)
      })
    }
  }
  dialog_xiangshanli.value=false
}
provide('perAllList', perAllList)

function lookUnivalence() {
  lookUnivalenceAPI({
    pageNum: null,
    pageSize: null
  }).then(data => {
    perAllList.value = data.data.data
  })
}

const dialog_xiangshanli = ref(false)
const xiangshanliList = ref([
  {
    department: "香山里中厨",
    rowNumber: 30,
    receivingPerson: ""
  },
  {
    department: "香山里点心",
    rowNumber: 15,
    receivingPerson: ""
  },
  {
    department: "香山里烧烤",
    rowNumber: 10,
    receivingPerson: ""
  },
  {
    department: "香山里取银",
    rowNumber: 10,
    receivingPerson: ""
  },
  {
    department: "香山里福食",
    rowNumber: 10,
    receivingPerson: ""
  },
  {
    department: "香山里刺身",
    rowNumber: 10,
    receivingPerson: ""
  }
])
watch(rid, () => {
  console.log("收货单位", rid.value)
  for (let i = 0; i < receiving_unitList.value.length; i++) {
    if (receiving_unitList.value[i].id === rid.value) {
      receiving_unit.value = receiving_unitList.value[i].name
      console.log("收货单位名称", receiving_unit.value)
      if (receiving_unit.value === "香山里酒楼") {
        dialog_xiangshanli.value = true
        break
      }
      break
    }
  }
})

function getConsignee() {
  getConsigneeAPI({
    pageNum: null,
    pageSize: null
  }).then(data => {
    console.log("receiving_unitList", data)
    receiving_unitList.value = data.data.data
  })
}

function getDate() {
  const now = new Date()
  const year = now.getFullYear() + '年'
  const month = ('0' + (now.getMonth() + 1)).slice(-2) + '月'
  const day = ('0' + now.getDate()).slice(-2) + '日'
  return year + month + day
}

//增加商品
function formTableAdd() {
  addGoodAllList.value.push({
    //商品id
    id: "",
    c_name: "",
    //数量
    number: "",
    //商品单位
    per: "",
    //单价
    costPrice: "",
    //备注
    remark: "",
    by: 1,
    //金额
    get money(): Number {
      return parseInt(this.number) * parseInt(this.costPrice)
    }
  })
}

function handleEdit() {
  if (!rid.value) {
    ElMessage.error("收货单位不能为空")
    return
  }
  if (!receivingPerson.value) {
    ElMessage.error("收货人不能为空")
    return
  }
  if (!department.value) {
    ElMessage.error("部门不能为空")
    return
  }
  if (addGoodAllList.value.length <= 0) {
    ElMessage.error("商品不能为空")
    return
  } else {
    for (let i = 0; i < addGoodAllList.value.length; i++) {
      if (!addGoodAllList.value[i].id) {
        ElMessage.error("商品名称不能为空")
        return
      }
      // if (!addGoodAllList.value[i].per) {
      //   ElMessage.error("商品单位不能为空")
      //   return
      // }
      if (!addGoodAllList.value[i].number) {
        ElMessage.error("商品数量不能为空")
        return
      }
      if (!addGoodAllList.value[i].costPrice) {
        ElMessage.error("商品单价不能为空")
        return
      }
    }
  }

  addGoodAllList.value.sort((a, b) => (a.c_name > b.c_name) ? 1 : ((b.c_name > a.c_name) ? -1 : 0));
  let j = 0
  for (let i = 0; i < addGoodAllList.value.length; i++) {
    addGoodAllList.value[j].by = 1
  }
  for (let i = 0; i < addGoodAllList.value.length; i++) {
    if (addGoodAllList.value[j].c_name != addGoodAllList.value[i].c_name) {
      j = i
    }
    addGoodAllList.value[j].by++
    addGoodAllList.value[i].by--
  }
  console.log("预览页面", addGoodAllList.value)
  for (let i = 0; i < addGoodAllList.value.length; i++) {
    goodList.value.push({
      id: "",
      cId: "",
      number: "",
      costPrice: "",
      per: "",
      remark: ""
    })
    goodList.value[i].number = addGoodAllList.value[i].number
    goodList.value[i].costPrice = addGoodAllList.value[i].costPrice
    goodList.value[i].per = addGoodAllList.value[i].per
    goodList.value[i].remark = addGoodAllList.value[i].remark
    for (let k = 0; k < goodsAllList.value.length; k++) {
      if (addGoodAllList.value[i].id == goodsAllList.value[k].name) {
        goodList.value[i].id = goodsAllList.value[k].id
        goodList.value[i].cId = goodsAllList.value[k].cid
      }
    }
  }
  dialogFormVisible.value = true
}

const goodsAllList = ref([])

function getGoods() {
  getGoodsAPI({
    pageNum: null,
    pageSize: null
  }).then(data => {
    console.log("Goods", data)
    goodsAllList.value = data.data.data.stockList
    console.log("全商品", goodsAllList.value)
  })
}

//删除
function formTableDelete(index) {
  addGoodAllList.value.splice(index, 1)
}

function addPrint() {
  dialogFormVisible.value = false
  console.log("goodList", goodList.value)
  console.log("receivingPerson", receivingPerson.value)
  console.log("department", department.value)
  console.log("remark", remark.value)
  console.log('rid', rid.value)
  addSalesAPI({
    rId: rid.value,
    receivingPerson: receivingPerson.value,
    department: department.value,
    remark: remark.value
  }, {
    stockList: goodList.value
  }).then(data => {
    console.log(data)
    ElMessage.success(data.data.data)
  })
  goodList.value = []
}

</script>
<template>
  <el-form
      label-width="auto"
      style="max-width: 900px"
  >

    <el-form-item
        label="收货单位:"
        class="min_width"
    >
      <el-select
          v-model="rid"
          placeholder="请输入收货单位"
          filterable
      >
        <el-option
            v-for="item in receiving_unitList"
            :label="item.name"
            :value="item.id"
        />
      </el-select>
    </el-form-item>

    <el-form-item
        label="收货人:"
        class="min_width"
    >
      <el-input
          v-model="receivingPerson"
          placeholder="请输入收货人"
      />
    </el-form-item>

    <el-form-item
        label="部门:"
        class="min_width"
    >
      <el-input
          v-model="department"
          placeholder="请输入部门"
      />
    </el-form-item>

    <el-form-item
        label="备注:"
        class="min_width"
    >
      <el-input
          v-model="remark"
          placeholder="请输入备注"
      />
    </el-form-item>

    <el-form-item
        label="销售商品:"
    >
      <el-button
          @click="formTableAdd"
      >增加
      </el-button>
      <div
          v-for="(item,index) in addGoodAllList"
          class="formTable_box"
      >
        <leave-store-item
            v-model:addGoodAllList="addGoodAllList"
            v-model:rid="rid"
            :index="index"
            :goodsAllList="goodsAllList"
        >
          <template #index>
            <div>
              <el-input
                  disabled="disabled"
                  :placeholder="`${index+1}`"
              >
                <template #prepend>
                  序号
                </template>
              </el-input>
            </div>
          </template>
          <template #button>
            <el-button
                @click="formTableDelete(index)"
                style="margin-left: 10px"
            >删除
            </el-button>
          </template>
        </leave-store-item>
      </div>
    </el-form-item>

    <el-form-item
        label="总数量:"
        class="min_width"
    >
      <el-input
          disabled="disabled"
          type="number"
          v-model="allNumber"
      />
    </el-form-item>

    <el-form-item
        label="总金额:"
        class="min_width"
    >
      <el-input
          disabled="disabled"
          type="number"
          v-model="allMoney"
      />
    </el-form-item>

    <el-form-item
        label="温馨提示:"
        class="min_width"
    >
      <template #default>
        <div>
          1.天气炎热,请收到货后及时放进冰箱储存
          <br>
          2.蔬菜允许土2%的误差,如有任何问题请在当天10:00前联系客服
          <br>
          3.请客户保存好菜筐,若有遗失按50元/个计算
        </div>
      </template>
      <!--      <el-input-->
      <!--          v-model="form.remark"-->
      <!--          type="textarea"-->
      <!--          placeholder="请输入提示"-->
      <!--          show-word-limit-->
      <!--          maxlength="250"-->
      <!--      />-->
    </el-form-item>

    <el-form-item
        label=" "
    >
      <el-button
          type="primary"
          @click="handleEdit"
      >打印
      </el-button>
    </el-form-item>
  </el-form>

  <el-dialog
      v-model="dialogFormVisible"
      width="750"
      title="预览"
  >
    <template #default>
      <div id="printJS-form" ref="printJS-form" class="dialog_from">
        <div class="dialog_title">广东裕诚餐饮管理服务有限公司配送单</div>

        <div class="dialog_recevingUnit">
          收货单位:{{ receiving_unit }}
        </div>
        <div class="dialog_recevingUnit">
          部门:{{ department }}
        </div>
        <div><span>送货日期:{{ getDate() }}</span>
          <span class="marginLeft">收货人:{{ receivingPerson }}</span>
        </div>
        <div>
          <table>
            <thead>
            <tr>
              <th>分类</th>
              <th>商品名称</th>
              <th>单位</th>
              <th>数量</th>
              <th>备注</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="item in addGoodAllList">
              <td v-if="item.by>=1" :rowspan="item.by">
                {{ item.c_name }}
              </td>
              <td>
                {{ item.id }}
              </td>
              <td>
                {{ item.per }}
              </td>
              <td>
                {{ item.number }}
              </td>
              <td>
                {{ item.remark }}
              </td>
            </tr>
            </tbody>
          </table>
        </div>
        <div>
          总数量:{{ allNumber }}
          总金额:{{ allMoney }}
        </div>
        <div class="footer_text">
          <div>
            温馨提示:
          </div>
          <div>
            1.天气炎热,请收到货后及时放进冰箱储存
          </div>
          <div>
            2.蔬菜允许土2%的误差,如有任何问题请在当天10:00前联系客服
          </div>
          <div>
            3.请客户保存好菜筐,若有遗失按50元/个计算
          </div>
        </div>
      </div>
    </template>
    <template #footer>
      <el-button
          type="primary"
          v-print="`#printJS-form`"
          @click="addPrint"
      >
        打印
      </el-button>
      <el-button
          @click="dialogFormVisible=false"
      >取消
      </el-button>
    </template>
  </el-dialog>

  <!--  香山里-->
  <el-dialog
      v-model="dialog_xiangshanli"
      width="100%"
      title="预览"
  >
    <template #default>
      <div id="printJS-form" ref="printJS-form" class="dialog_from">
        <div class="dialog_title">广东裕诚餐饮管理服务有限公司配送单</div>
        <div class="formDialog_xiangshanli">
          <div
              v-for="(item,index) in xiangshanliList"
              style="margin-bottom: 30px"
          >
            <xiangshanli
                :department="item.department"
                :rowNumber="item.rowNumber"
                :rid="rid"
                v-model="xiangshanli_List[index]"
                :goodsAllList="goodsAllList"
            >
              <div><span>送货日期:{{ getDate() }}</span>
                <span class="marginLeft">收货人:
                  <el-input
                      v-model="item.receivingPerson"
                      style="width: 160px;"
                      size="small"
                  />
                </span>
              </div>
            </xiangshanli>
          </div>
        </div>

      </div>
    </template>
    <template #footer>
      <el-button
          type="primary"
          v-print="`#printJS-form`"
          @click="addPrint_xiangshanli"
      >
        打印
      </el-button>
<!--      <el-button-->
<!--          @click="addPrint_xiangshanli"-->
<!--      >-->
<!--        测试-->
<!--      </el-button>-->
      <el-button
          @click="dialog_xiangshanli=false"
      >取消
      </el-button>
    </template>
  </el-dialog>
</template>
<style scoped>
@import "@/assets/print.css";

.min_width {
  width: 500px;
}

.formTable_box {
  margin-top: 10px;
}

.formTable {
  display: flex;
  width: 100%;
  margin-top: 10px;
}

.formDialog_xiangshanli {
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
  height: 1850px;
}
</style>